/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "MC_include.h"
#include "GUI.h"
#include "DIALOG.h"
#include "string.h"

/********相关函数**********/
void SystemClock_Config(void);
static void GUI_Task(void* parameter);
void AppTaskStart(void *argument);
static void AppTaskCreate (void);
/***************************/

/***********邮箱定义*************/
/********************************/

extern uint32_t pul_conut;

FATFS fs;//逻辑磁盘工作区.
BYTE work[FF_MAX_SS]; /* Work area (larger is better for processing time) */

const osThreadAttr_t ThreadStart_Attr =
{
    .name = "osRtxStartThread",
    .attr_bits = osThreadDetached,
    .priority = osPriorityLow,
    .stack_size = 512,
};

const osThreadAttr_t GUI_Task_Attr =
{
    .name = "guiThread",
    .attr_bits =  osThreadDetached,
    .priority = osPriorityNormal,
    .stack_size = 1024*6,
};

const osThreadAttr_t TOUCH_Task_Attr =
{
    .name = "toucThread",
    .attr_bits =  osThreadDetached,
    .priority = osPriorityNormal1,
    .stack_size = 512,
};
const osThreadAttr_t hstepperLimit_Task_Attr =
{
    .name = "shouDongYunxing",
    .attr_bits =  osThreadDetached,
    .priority = osPriorityNormal2,
    .stack_size = 512,
};

osThreadId_t ThreadIdGUI = NULL;
osThreadId_t ThreadIdTouch = NULL;
osThreadId_t ThreadIdLimit = NULL;
osThreadId_t ThreadIdStart = NULL;
/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
    HAL_Init();
    SystemClock_Config();

    /* 内核开启前关闭HAL的时间基准 */
    HAL_SuspendTick();
    /* 内核初始化 */
    osKernelInitialize();

    ThreadIdStart = osThreadNew(AppTaskStart, NULL, &ThreadStart_Attr);
    /* 开启多任务 */
    osKernelStart();
    printf("RTX5 Started.\r\n");

    while(1);
}

void bsp_Init(void)
{
    int res;
    char ch;
    beep_gpio_init();
    MX_USART1_UART_Init();
    rs485_init();
    stepper_Init();
    motor_gpio_init();
    limit_gpio_init();
    lcd_gpio_init();
	MX_I2C2_Init();
    W25QXX_Init();				    //初始化W25Q256
    SDRAM_Init();                   //初始化SDRAM
    LCD_Init();                     //初始化LCD
    tp_dev.init();				    //触摸屏初始化
	parameter_init();
    my_mem_init(SRAMIN);		    //初始化内部内存池
    my_mem_init(SRAMEX);		    //初始化外部内存池
    my_mem_init(SRAMCCM);		    //初始化CCM内存池
    res = f_mount(&fs, "1:", 1); 				//挂载FLASH.

    if(res == FR_NO_FILESYSTEM) //FLASH磁盘,FAT文件系统错误,重新格式化FLASH
    {
        LCD_ShowString(30, 150, 200, 16, 16, "Flash Disk Formatting...");	//格式化FLASH
        printf("Flash disk don't have file system.\r\n");
        printf("Input Y format the disk, N skip\r\n");
        scanf("%c", &ch);

        if(ch == 'Y')
        {
            res = f_mkfs("1:", 0, work, 512); //格式化FLASH,1,盘符;1,不需要引导区,8个扇区为1个簇

            if(res == 0)
            {
                f_setlabel((const TCHAR *)"1:LOCAL0");	//设置Flash磁盘的名字为：LOCAL0
                LCD_ShowString(30, 150, 200, 16, 16, "Flash Disk Format Finish");	//格式化完成
            }
            else LCD_ShowString(30, 150, 200, 16, 16, "Flash Disk Format Error ");	//格式化失败
        }

        delay_ms(1000);
    }
    else
        printf("Flash disk mountted %d\r\n", res);

    __HAL_RCC_CRC_CLK_ENABLE();
}

/**
  * @brief GUI任务主体
  * @note 无
  * @param 无
  * @retval 无
  */
static void GUI_Task(void* parameter)
{
    WM_SetCreateFlags(WM_CF_MEMDEV);//要加上这句话，允许存储器
    GUI_Init();/* 初始化GUI */
    WM_MULTIBUF_Enable(1);/* 开启三缓冲 */
    GUI_EnableAlpha(1);

    while(1)
    {
        MainTask();
    }
}

//TOUCH任务
void touch_task(void *parameter)
{
    while(1)
    {
        GUI_GetOnoPiont();
        osDelay(20);
    }
}


extern signed char stepper_run_flag[3];
extern uint8_t limit_en[3];
void stepperLimit_task(void *parameter)
{
    while(1)
    {
        limit_check(limit_en);

        if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_4))
        {
            limit_en[0] = 1;
        }

        if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_12))
        {
            limit_en[1] = 1;
        }

        if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1))
        {
            limit_en[2] = 1;
        }

        osDelay(5);
    }
}

void AppTaskStart(void *argument)
{
    const uint16_t usFrequency = 1; /* 延迟周期 */
    uint32_t tick;

    /* 初始化外设 */
    HAL_ResumeTick();
    bsp_Init();

    /* 创建任务 */
    AppTaskCreate();

    /* 获取当前时间 */
    tick = osKernelGetTickCount();

    while(1)
    {
        /* 需要周期性处理的程序，对应裸机工程调用的SysTick_ISR */
        //bsp_ProPer1ms();

        /* 相对延迟 */
        tick += usFrequency;
        osDelayUntil(tick);
    }
}


/*
*********************************************************************************************************
*	函 数 名: AppTaskCreate
*	功能说明: 创建应用任务
*	形    参: 无
*	返 回 值: 无
*********************************************************************************************************
*/
static void AppTaskCreate (void)
{
    ThreadIdGUI = osThreadNew(GUI_Task, NULL, &GUI_Task_Attr);  /* 创建GUI任务 */
    ThreadIdTouch = osThreadNew(touch_task, NULL, &TOUCH_Task_Attr);  /* 创建GUI任务 */
    ThreadIdLimit = osThreadNew(stepperLimit_task, NULL, &hstepperLimit_Task_Attr);  /* 创建限位任务任务 */
}
/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};

    /** Configure the main internal regulator output voltage
    */
    __HAL_RCC_PWR_CLK_ENABLE();
    __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
    /** Initializes the RCC Oscillators according to the specified parameters
    * in the RCC_OscInitTypeDef structure.
    */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
    RCC_OscInitStruct.PLL.PLLM = 8;
    RCC_OscInitStruct.PLL.PLLN = 180;
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
    RCC_OscInitStruct.PLL.PLLQ = 4;

    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }

    /** Activate the Over-Drive mode
    */
    if (HAL_PWREx_EnableOverDrive() != HAL_OK)
    {
        Error_Handler();
    }

    /** Initializes the CPU, AHB and APB buses clocks
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
                                  | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
    {
        Error_Handler();
    }

    PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LTDC;
    PeriphClkInitStruct.PLLSAI.PLLSAIN = 90;
    PeriphClkInitStruct.PLLSAI.PLLSAIR = 2;
    PeriphClkInitStruct.PLLSAIDivR = RCC_PLLSAIDIVR_2;

    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
}


/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();

    while (1)
    {
    }

    /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN 6 */
    /* User can add his own implementation to report the file name and line number,
       ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
